class Ad < ActiveRecord::Base
  has_many :galleries
  has_many :judgements
  has_many :buyers, :through => :judgements
  #has_one :seller, :through => :judgement
  has_many :reports
  has_many :pictures, :through => :galleries
  has_many :ad_categories
  has_many :categories, :through => :ad_categories
  belongs_to :user
  has_one :auction
  has_one :fixed_ad
  #has_one :fixed, :through => :fixed_ad
  has_one :relaxed
  has_many :ad_shipping_methods
  has_many :ad_subscriptions
  has_many :ad_payment_methods
  has_many :payment_methods, :through => :ad_payment_methods
  belongs_to :ad_status
  belongs_to :ad_type

  validates_length_of :title,  :in => 5..50
  validates_length_of :description,  :in => 10..5000
  #validates_presence_of :enddate

  def fixed
    if fixed_ad
      return fixed_ad.fixed
    elsif auction && auction.fixed
      return auction.fixed
    end
    return nil
  end

  def to_param
    "#{id}-" + title.downcase.gsub(/[åä]+/,'a').gsub(/[ö]+/,'o').gsub(/[^a-z0-9\s_-]+/,'').gsub(/[\s_-]+/,'-')
  end

  def self.search(query, category, limit, province, county)
    require 'fast_search/RubySearch'
    RubySearch.search(query, category, limit, province, county)
    #require 'fast_search/NetSearch'
    #NetSearch.search(query, category, limit, province, county)
  end

  def pictures_hash
    hash = Hash.new
    pictures.each do |p|
      hash[p.id] = true
    end
    hash
  end

  def categories_hash
    hash = Hash.new
    categories.each do |p|
      hash[p.id] = true
    end
    hash
  end

  def payment_hash
    hash = Hash.new
    ad_payment_methods.each do |p|
      hash[p.payment_method_id] = true
    end
    hash
  end

  def remove
    AdCategory.delete(ad_categories)
    AdPaymentMethod.delete(ad_payment_methods)
    AdShippingMethod.delete(ad_shipping_methods)
    AdSubscription.delete(ad_subscriptions)

    if (auction)
      Bid.delete(auction.bids)
      DynamicAuction.delete(auction.dynamic_auction) if auction.dynamic_auction
      Fixed.delete(auction.fixed)  if auction.fixed
      FixedAuction.delete(auction.fixed_auction) if auction.fixed_auction
      Auction.delete(auction)
    end

    if (fixed_ad)
      Fixed.delete(fixed_ad.fixed)
      FixedAd.delete(fixed_ad)
    end

    Gallery.delete(galleries)

    if (relaxed)
      Relaxed.delete(relaxed)
    end

    Report.delete(reports)

    Ad.delete(id)
  end

  def buy(user)
    if (ad_status_id != 5 && fixed)
      judgement = Judgement.new
      judgement.buyer_id = user.id
      judgement.seller_id = user_id
      judgement.ad_id = id
      judgement.save

      fixed.quantity -= 1
      fixed.save
      if fixed.quantity <= 0
        self.ad_status_id = 5
        save
      end

      Email.notifyAdBought(self,user)
    end
  end
end
